package com.itheima.cs.common.nbdb;

import android.os.Bundle;
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.itheima.cs.R;
import com.itheima.cs.adapter.dbd.StockAdapter;
import com.itheima.cs.dao.dbd.WarehouseDao;
import com.itheima.cs.entity.dbd.WarehouseInfo;

import java.util.ArrayList;
import java.util.List;

public class StockSelectActivity extends AppCompatActivity {
    private EditText etSearch;
    private StockAdapter adapter;
    private List<WarehouseInfo> dataList = new ArrayList<>();
    private WarehouseInfo selectedStock;

    private String stockProperty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stock_select);

        stockProperty = getIntent().getStringExtra("stock_property");

        initToolbar();
        initViews();
        performSearch();
    }

    private void initToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar_stock_select);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(v -> finish());
    }

    private void initViews() {
        etSearch = findViewById(R.id.et_search);
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        adapter = new StockAdapter(dataList, this::onStockSelected);
        recyclerView.setAdapter(adapter);

        findViewById(R.id.btn_search).setOnClickListener(v -> performSearch());
        findViewById(R.id.btn_confirm).setOnClickListener(v -> {
            if (selectedStock != null) {
                Intent resultIntent = new Intent();
                resultIntent.putExtra("selected_stock", selectedStock);
                setResult(RESULT_OK, resultIntent);
                finish();
            } else {
                Toast.makeText(this, "请选择仓库", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void performSearch() {
        String keyword = etSearch.getText().toString().trim();

        new Thread(() -> {
            List<WarehouseInfo> result = new WarehouseDao().searchWarehouses(keyword,stockProperty);
            runOnUiThread(() -> {
                dataList.clear();
                dataList.addAll(result);
                adapter.notifyDataSetChanged();
            });
        }).start();
    }

    private void onStockSelected(WarehouseInfo stock) {
        selectedStock = stock;
    }
}